﻿Imports Aricie.DNN.UI.WebControls
Imports Aricie.Collections
Imports System.Linq
Imports DotNetNuke.Services.Localization

Namespace Aricie.DNN.Services.Url.FriendlyUrl.Controls
    Public Class Aliases
        Inherits PropertyEditorUserControlBase

        Public Property Aliases As SerializableDictionary(Of String, FriendlierUrlRule)
            Get
                Return DirectCast(Me.Value, SerializableDictionary(Of String, FriendlierUrlRule))
            End Get
            Set(value As SerializableDictionary(Of String, FriendlierUrlRule))
                Me.Value = value
            End Set
        End Property


         Private _CurrentSettings As FriendlierUrlSettings

        Public ReadOnly Property CurrentSettings As FriendlierUrlSettings
            Get
                 if _CurrentSettings Is nothing
                    _CurrentSettings = Me.EditControl.ParentAricieEditor.GetParentEntity(of FriendlierUrlSettings)
                End If
                Return _CurrentSettings
            End Get
        End Property

        Public Property CurrentAlias As String
            Get
                'If ViewState("CurrentAlias") Is Nothing Then
                '    ViewState("CurrentAlias") = String.Empty
                'End If

                'Return DirectCast(ViewState("CurrentAlias"), String)

                If DnnContext.Current.AdvancedClientVariable(Me, "CurrentAlias").IsNullOrEmpty() Then
                    DnnContext.Current.AdvancedClientVariable(Me, "CurrentAlias") = String.Empty
                End If

                Return DnnContext.Current.AdvancedClientVariable(Me, "CurrentAlias")
            End Get
            Set(value As String)
                DnnContext.Current.AdvancedClientVariable(Me, "CurrentAlias") = value
            End Set
        End Property

        Protected Sub Loading(sender As Object, e As System.EventArgs) Handles Me.Init
            gaActuel.SharedResourceFileOverride = Me.SharedResourceFile
            gaActuel.Value = New FriendlierUrlRule

            If Aliases.ContainsKey(CurrentAlias) Then
                SetEditionToAlias(CurrentAlias)
                'gaActuel.Value = Aliases(CurrentAlias)
            Else
                gaActuel.Value = New FriendlierUrlRule
            End If

            lblErrorMessage.Text = String.Empty
            BindAliasList()
        End Sub

        Private Sub BindAliasList()
            Dim NoDeletionMessage As String = Localization.GetString("NoDeletion.Message", LocalResourceFile)
            rAliases.DataSource = Aliases.Keys.Select(Function(s) New With {.Name = s _
                                                                           , .CanBeDeleted = Not AliasIsInUse(s) _
                                                                            , .NoDeletionMessage = NoDeletionMessage _
                                                                           , .Class = IIf(s = CurrentAlias, "ActiveAlias ", "")})
            rAliases.DataBind()
        End Sub

        Private Function AliasIsInUse(AliasName As String) As Boolean
            Dim ListBehaviours As New List(Of FriendlierUrlStrategy)
            ListBehaviours.Add(CurrentSettings.DefaultBehaviour)
            ListBehaviours.AddRange(CurrentSettings.ModuleSpecificBehaviour.Values.Cast(Of FriendlierUrlStrategy))
            ListBehaviours.AddRange(CurrentSettings.TabSpecificBehaviour.Values.Cast(Of FriendlierUrlStrategy))

            Return ListBehaviours.Any(Function(FUS) AliasInUse(AliasName, FUS))
        End Function

        Private Function AliasInUse(AliasName As String, FUS As FriendlierUrlStrategy) As Boolean
            Return FUS.FriendlyRule.Instances.Cast(Of UrlGroup).Any(Function(UG) TypeOf UG Is AliasUrlGroup AndAlso DirectCast(UG, AliasUrlGroup).AliasName = AliasName)
        End Function

        Private Sub btnAdd_Click(sender As Object, e As System.EventArgs) Handles btnAdd.Click
            If Aliases.Keys.Select(Function(s) s.ToLower()).Any(Function(s) s = tbAlias.Text) OrElse String.IsNullOrEmpty(tbAlias.Text) Then
                If String.IsNullOrEmpty(tbAlias.Text) Then
                    lblErrorMessage.Text = Localization.GetString("rfvAlias.ErrorMessage", LocalResourceFile)
                Else
                    lblErrorMessage.Text = Localization.GetString("revAlias.ErrorMessage", LocalResourceFile)
                End If
                Exit Sub
            End If

            Dim EditedAliases As SerializableDictionary(Of String, FriendlierUrlRule) = Aliases
            EditedAliases.Add(tbAlias.Text, New FriendlierUrlRule())
            Aliases = EditedAliases

            SetEditionToAlias(tbAlias.Text)
            BindAliasList()

            tbAlias.Text = String.Empty
        End Sub

        Public Sub EditAlias(sender As Object, e As System.Web.UI.WebControls.CommandEventArgs)
            SetEditionToAlias(e.CommandArgument.ToString())
            BindAliasList()
        End Sub

        Private Sub SetEditionToAlias(key As String)
            If (Aliases.ContainsKey(key)) Then
                gaActuel.Value = Aliases(key)
                gaActuel.Groups = Aliases(key).Instances
                gaActuel.SetInnerPropertyEditor()
                CurrentAlias = key
                gaActuel.Visible = True
            Else
                gaActuel.Visible = False
            End If
        End Sub

        Public Sub DeleteAlias(sender As Object, e As System.Web.UI.WebControls.CommandEventArgs)
            Dim DeleteAliasName As String = e.CommandArgument.ToString()
            If CurrentAlias = e.CommandArgument.ToString() Then
                SetEditionToAlias(String.Empty)
            End If
            Dim EditedAliases As SerializableDictionary(Of String, FriendlierUrlRule) = Aliases
            EditedAliases.Remove(DeleteAliasName)
            Aliases = EditedAliases
            BindAliasList()
        End Sub

        Protected Overrides Sub OnPreRender(e As System.EventArgs)
            btnAdd.Text = Localization.GetString("btnAdd.Text", LocalResourceFile)



            If TrialMode IsNot Nothing Then
                btnAdd.Enabled = False
                btnAdd.ToolTip = Localization.GetString("TrialMode.Disabled", SharedResourceFile)
                gaActuel.TrialMode = TrialMode
            End If

            MyBase.OnPreRender(e)
        End Sub

        Private Sub gaActuel_AvailableProvidersEvent(APEA As UrlGroups.AvailableProvidersEventArgs) Handles gaActuel.AvailableProvidersEvent
            APEA.Providers = FriendlierUrlConfig.Instance.DefaultUrlProviders
        End Sub
    End Class
End Namespace